import Image
from datetime import date
from time import time
import logging
import os
import traceback
from django.contrib.auth.decorators import login_required
from django.db.models.query_utils import Q
from django.http import HttpResponse, Http404
from django.conf import settings
from apps.news.models import RecordImage
from core.decorators import render
from core.enum import REQUEST_POST
from core.forms.admin import UploadFileForm
from django.views.decorators.csrf import csrf_exempt
from core.libs.translit import translify
from django.http import HttpResponseRedirect
from subprocess import call

def run_parser(request):
    #os.system("python /var/www/vhosts/iziparser/parser.py")
    call("python /var/www/vhosts/iziparser/parser.py &", shell=True)
    return HttpResponseRedirect(request.META.get('HTTP_REFERER','/'))

@csrf_exempt
@render(type='json')
def files_delete(request):
    pks = request.POST.get('ids').split(',')
    items = RecordImage.objects.filter(pk__in = pks)
    for item in items:
        os.remove("%s%s" % (settings.LIVE_ENGINE_UPLOAD_PATH, item.image))
        item.delete()
    return {}

@csrf_exempt
@render(type='json')
def files_list(request):
    record_pk = request.REQUEST.get('pk', None)
    items = RecordImage.objects.filter(
        Q(record__pk = record_pk) |
        Q(record = None)
    ).order_by('record')
    
    images = []
    for item in items:
        images.append({
            'id': item.pk,
            'image': item.image,
            'thumbnail': item.thumbnail,
            'record': item.record.pk if item.record else None,
            'url': "%s%s" % (settings.LIVE_ENGINE_UPLOAD_URL, item.image)
        })

    return {
        'images': images
    }


@csrf_exempt
def file_upload(request):

    logger = logging.getLogger()
    logger.info("Admin file upload entry point")

    try:
        # catalog

        current_upload_folder = "%s%s/" % (settings.LIVE_ENGINE_UPLOAD_PATH, date.today().strftime("%Y-%m"))
        if not os.path.exists(current_upload_folder):
            os.makedirs(current_upload_folder)
            os.makedirs("%sthumbs" % current_upload_folder)

        if request.method == REQUEST_POST:
            form = UploadFileForm(request.POST, request.FILES)
            logger.info(request.POST)
            if form.is_valid():
                file = request.FILES['Filedata']

		tmp_name = "%s-%s" % (
		    int(time()),
		    translify(file.name.lower())
		)

                file_name = "%s/%s" % (
                    date.today().strftime("%Y-%m"),
		    tmp_name
                )

                uploaded_file = open("%s%s" % (settings.LIVE_ENGINE_UPLOAD_PATH, file_name), "w")
                uploaded_file.write(file.read())
                uploaded_file.close()

                thumbnail_image = None

                img = Image.open("%s%s" % (settings.LIVE_ENGINE_UPLOAD_PATH, file_name))
                if img.size[0] > settings.LIVE_ENGINE_UPLOAD_RESIZE_WIDTH:
                    resize = float(settings.LIVE_ENGINE_UPLOAD_RESIZE_WIDTH)/float(img.size[0])
                    thumbnail = img.resize((
                        settings.LIVE_ENGINE_UPLOAD_RESIZE_WIDTH,
                        int(img.size[1]*resize)
                    ), Image.ANTIALIAS)
                    thumbnail_image = "%s%s/thumbs/%s" % (
                        settings.LIVE_ENGINE_UPLOAD_PATH,
                        date.today().strftime("%Y-%m"),
                        tmp_name
                    )
                    thumbnail.save(
                        thumbnail_image
                    )

                RecordImage.objects.create(
                    image = file_name,
                    thumbnail = thumbnail_image
                )
                
                return HttpResponse('File successfully loaded')
            else:
                logger.error("%s" % form.errors)

        raise Http404

    except Exception, e:
        traceback.print_exc()
        logger.error(traceback.format_exc())
